import { Component, OnInit } from '@angular/core'
import { FormBuilder } from '@angular/forms'
import { NzMessageService } from 'ng-zorro-antd'

import { StoreNewBaseClass } from '../baseClass'
import { StoreDataService } from '../../store-data.service'
import { makeAllControlDirty } from 'app/utils/helpers'
import { ICardTradeType } from './card-func.interface'
import { I18NService } from '@core'

@Component({
  selector: 'app-store-new-card-func',
  templateUrl: './card-func.component.html',
})
export class StoreNewCardFuncComponent extends StoreNewBaseClass implements OnInit {
  tradeTypes: string[] = []
  tradeTypeOptions: ICardTradeType[] = [
    {
      label: '消费',
      value: 'todo0',
      checked: false,
    },
    {
      label: '预授权',
      value: 'todo1',
      checked: false,
    },
    {
      label: '退款',
      value: 'todo2',
      checked: false,
    },
    {
      label: '手输卡号消费',
      value: 'todo3',
      checked: false,
    },
    {
      label: '预授权完成',
      value: 'todo4',
      checked: false,
    },
    {
      label: '手输卡号预授权',
      value: 'todo5',
      checked: false,
    }
  ]

  constructor(
    public fb: FormBuilder,
    public storeService: StoreDataService,
    private i18n: I18NService,
    private msg: NzMessageService
  ) {
    super(fb, storeService)
  }

  ngOnInit() {
    this.initValidateForm()
  }

  initValidateForm(): void {
    const { tradeTypes } = this.store.store.card
    this.tradeTypeOptions.forEach(option => {
      if (tradeTypes.includes(option.value)) {
        option.checked = true
      }
    })
    this.validateForm = this.fb.group({
      tradeTypes: [this.tradeTypeOptions, []],
    })
  }

  pushDataToStore(): void {
    const { card } = this.store.store
    const tmp = this.validateForm.value
    tmp.tradeTypes = this.getCheckedTradeType(this.validateForm.value.tradeTypes)
    tmp.isRefundAsync = tmp.isRefundAsync === 'true' ? true : false
    Object.assign(card, tmp)
    this.storeStore.updateValue(this.store)
  }

  getCheckedTradeType(tradeTypes: ICardTradeType[]): string[] {
    return tradeTypes.filter(ty => ty.checked).map(ty => ty.value)
  }

  checkValid(): boolean {
    if (this.validateForm.valid) {
      this.pushDataToStore()
      return true
    }
    makeAllControlDirty(this.validateForm)
    this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    return false
  }

  renderTradeTypeOptions(tradeType: string[]) {
    this.tradeTypeOptions.forEach(option => {
      if (tradeType.includes(option.value)) {
        option.checked = true
      }
    })
  }

  analyseTradeTypeOptions(tradeTypeOptions: any[]): string[] {
    return tradeTypeOptions
      .filter(option => option.checked)
      .map(option => option.value)
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
